/*!
 * \file cics_mar.c
 *
 * \brief 底层数据操作
 *
 * All Rights Reserved Copyright (C) 2014 broada,Co.,Ltd.
 *
 * \version 1.0
 * \author songbb
 * \date 2015/10/07
 *
 */

#include <iconv2utf8.h>

#include "cics_core.h"
#include "cics_mar.h"
#include "cics_comm.h"

int cics_mar_get_boolean(L7_cics_packet *p_st_cics_packet
                        , int *p_i_out)
{
    unsigned char uc_tmp = 0;
    if (bytebuff_get_char(p_st_cics_packet->p_st_packet, &uc_tmp) != FR_SUCC)
        return FR_FAIL;
    *p_i_out = uc_tmp != 0 ? FR_YES : FR_NO;
    return FR_SUCC;
}

int cics_mar_get_string(L7session_cics *p_st_sess
                        , L7_cics_packet *p_st_cics_packet
                        , unsigned int ui_len
                        , char **pp_out)
{
    char *p_outtmp = NULL;
    char *p_buff_out = NULL;
    unsigned int ui_out_len = 0;

    if (ui_len > 0)
    {
        if ((p_outtmp = (char *) frmalloc(ui_len * sizeof(char))) == NULL)
        {
            CICS_MALLOCK_ERR;
            goto error;
        }
        if (bytebuff_get_bytes(p_st_cics_packet->p_st_packet, p_outtmp, ui_len) != FR_SUCC)
            goto error;

        if (p_st_sess->p_encoding != NULL)
        {
            if (iconv_to_utf8(p_outtmp, ui_len, p_st_sess->p_encoding, &p_buff_out, &ui_out_len) == FR_SUCC)
                goto success;
            cics_free((void **) &p_buff_out);
        }

        if ((p_buff_out = (char *) frmalloc((ui_len + 1) * sizeof(char))) == NULL)
        {
            CICS_MALLOCK_ERR;
            goto error;
        }
        memcpy(p_buff_out, p_outtmp, ui_len);
        p_buff_out[ui_len] = '\0';
    }

success:
    cics_free((void **) &p_outtmp);
    *pp_out = p_buff_out;
    return FR_SUCC;
error:
    cics_free((void **) &p_outtmp);
    cics_free((void **) &p_buff_out);
    return FR_FAIL;
}

int cics_mar_get_utf(L7_cics_packet *p_st_cics_packet
                    , char **pp_out
                    , unsigned int *p_ui_out_len)
{
    uint16_t s_utflen = 0;
    char *p_outtmp = NULL;

    if (bytebuff_get_short(p_st_cics_packet->p_st_packet, 2, &s_utflen, BYTE_BIG_ENDIAN) != FR_SUCC)
        goto error;

    if (s_utflen > 0)
    {
        if ((p_outtmp = (char *) frmalloc((s_utflen + 1) * sizeof(char))) == NULL)
        {
            CICS_MALLOCK_ERR;
            goto error;
        }
        if (bytebuff_get_bytes(p_st_cics_packet->p_st_packet, p_outtmp, s_utflen) != FR_SUCC)
            goto error;
        p_outtmp[s_utflen] = '\0';
    }

    *pp_out = p_outtmp;
    *p_ui_out_len = s_utflen;

    return FR_SUCC;
error:
    cics_free((void **) &p_outtmp);
    return FR_FAIL;
}
